package org.sunrise.game.global.service.chat;

import org.sunrise.game.global.gen.CallEnum;
import org.sunrise.game.rpc.annotation.RpcMethod;
import org.sunrise.game.rpc.annotation.RpcService;
import org.sunrise.game.rpc.function.RpcFunction;
import org.sunrise.game.rpc.service.BaseService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 跨服聊天系统
 */
@RpcService
public class ChatService extends BaseService {
    // 定义最大聊天记录数量
    private static final int MAX_MESSAGES = 50;
    private final List<ChatData> messages = new LinkedList<>();

    public ChatService(String nodeId) {
        super(nodeId);
    }

    @RpcMethod
    public void chat(String humanId, int type, String message) {
        if (type == ChatType.GLOBAL) {
            long time = System.currentTimeMillis();
            messages.add(new ChatData(humanId, time, message));

            if (messages.size() > MAX_MESSAGES) {
                messages.removeFirst();
            }

            RpcFunction.newInstance(RpcFunction.RpcCallType.SendAll)
                    .call(CallEnum.ChatRpcListenService_onChat, "humanId", humanId, "type", type, "message", message, "time", time);
        }
    }

    @RpcMethod
    public void history(String humanId, int type) {
        if (type == ChatType.GLOBAL) {
            List<String> ids = new ArrayList<>();
            List<String> msgs = new ArrayList<>();
            List<Long> times = new ArrayList<>();

            for (ChatData message : messages) {
                ids.add(message.getHumanId());
                msgs.add(message.getMessage());
                times.add(message.getSendTime());
            }
            RpcFunction.newInstance(RpcFunction.RpcCallType.SendAll)
                    .call(CallEnum.ChatRpcListenService_onHistory, "humanId", humanId, "type", type, "ids", ids, "msgs", msgs, "times", times);
        }
    }
}
